package com.LeeCode;

import java.util.LinkedList;
import java.util.Queue;

public class Utils {

    public static ListNode arrayToListNode(int[] arr) { // 用于将数组转化为链表
        if (arr == null || arr.length == 0) {
            return null; // 如果数组为空，返回 null
        }
        // 创建链表的头节点
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;

        // 遍历数组，依次创建链表节点
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }

        return head; // 返回链表的头节点
    }

    public static void printListNode(ListNode head) { // 用于打印链表
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
    }

    public static TreeNode buildTree(Integer[] nums) {

        if (nums == null || nums.length == 0 || nums[0] == null) return null;

        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(nums[0]);
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < nums.length) {
            TreeNode current = queue.poll();

            // 左孩子
            if (index < nums.length && nums[index] != null) {
                current.left = new TreeNode(nums[index]);
                queue.offer(current.left);
            }
            index++;

            // 右孩子
            if (index < nums.length && nums[index] != null) {
                current.right = new TreeNode(nums[index]);
                queue.offer(current.right);
            }
            index++;
        }

        return root;
    }

    public static void main(String[] args) {
        Integer[] arr = {1,2,null,3,4,5,null,6};
        TreeNode root = buildTree(arr);
        System.out.println(root);
    }

}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
